from django.conf import settings
from eventlet.patcher import monkey_patch
from rest_framework import status
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from fdfs_client.client import Fdfs_client

from goods.models import SKUImage, SKU
from meiduo_admin.serialziers.images import ImageSerializer, SKUSerializer
from meiduo_admin.utils.page import PageNum
from celery_tasks.detail.tasks import generate_static_sku_detail_html

from celery_tasks.detail.tasks import delete_static_sku_detail_html


class ImageView(ModelViewSet):
    """
    图片的逻辑操作
    """
    # 权限指定
    permission_classes = [IsAdminUser]
    # 图片查询集
    queryset = SKUImage.objects.all()
    # 图片序列化器
    serializer_class = ImageSerializer
    # 分页
    pagination_class = PageNum

    # def create(self, request, *args, **kwargs):
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     self.perform_create(serializer)
    #     headers = self.get_success_headers(serializer.data)
    #     # 异步生成详情页静态页面
    #     print(serializer)
    #     generate_static_sku_detail_html.delay(serializer.validated_data['sku_id'])
    #     return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def update(self, request, *args, **kwargs):
        permission_classes = [IsAdminUser]

        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        # 异步生成详情页静态页面
        generate_static_sku_detail_html.delay(instance.sku_id)
        return Response(serializer.data)

    def destroy(self, request, *args, **kwargs):
        """
        删除商品图片我们需要删除对应生成的静态网页
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        permission_classes = [IsAdminUser]

        instance = self.get_object()
        self.perform_destroy(instance)
        delete_static_sku_detail_html(instance.sku_id)
        return Response(status=status.HTTP_204_NO_CONTENT)

    # 获取sku商品信息
    def simple(self, request):
        data = SKU.objects.all()
        ser = SKUSerializer(data, many=True)
        return Response(ser.data)
